import { showToast, requestPayment } from "../../utils/asyncWx.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
import { request } from "../../request/index.js";
Page({

    data: {
        cart: {},
        totalPrice: 0,
        token: "",
        orderSn: '',
        showModalDlg: false
    },
    QueryParams: {
        skuId: "",
        num: 1,
        payAmount: 0
    },

    onLoad() {
        const token = wx.getStorageSync("token");
        let cart = wx.getStorageSync("cart");
        this.setData({
            token,
            cart: cart,
            totalPrice: cart.price,
        });
    },

    // 改变数量
    async handleItemNumEdit(e) {
        // 获取传递过来的参数
        const { operation } = e.currentTarget.dataset;
        // // 获取购物车数组
        let { cart } = this.data;
        cart.num += operation;
        let totalPrice = cart.num * cart.price;
        this.setData({
            cart,
            totalPrice
        })
    },

    // 去支付
    async toTrade() {
        this.QueryParams.skuId = this.data.cart.id;
        this.QueryParams.num = this.data.cart.num;
        this.QueryParams.payAmount = this.data.totalPrice;

        // 4 准备发送请求 创建订单 获取订单编号
        const result = await request({
            url: "/order/order/app/submitOrder",
            method: "POST",
            data: this.QueryParams,
            header: { "token": this.data.token }
        });

        // 5 创建订单成功 显示支付模态框
        if (result.code == 0) {
            this.setData({
                totalPrice: parseFloat(this.data.totalPrice).toFixed(2),
                orderSn: result.data.order.orderSn,
                showModalDlg: true
            });
        }
    },


    // 点击支付按钮
    async handleOrderPay() {
        // 6 发起 支付接口
        const orderSn = this.data.orderSn;
        const result = await request({
            url: "/order/app/payed/notify",
            data: { "orderSn": orderSn }
        });

        if (result.code == 0) {
            // 7 支付成功 跳转到订单页面 删除缓存中的商品
            wx.reLaunch({
                url: '/pages/orderDetail/orderDetail?orderSn=' + orderSn
            });
        }
    },


    // 取消支付 跳转到订单页面
    cancelModal() {
        var that = this;
        wx.showModal({
            title: '取消支付',
            success(res) {
                if (res.confirm) {
                    that.setData({ showModalDlg: false });
                    wx.reLaunch({
                        url: '/pages/order/order'
                    });
                } else if (res.cancel) {
                    that.setData({ showModalDlg: true });
                }
            }
        });
    }
})